package com.organization

import grails.test.*

class ProjectServiceTests extends GrailsUnitTestCase {
    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testServiceMethods() {
        //create testing service
        def testService = new ProjectService()

        //mock commonService methods
        def mockControl = mockFor(CommonService,true)
        mockControl.demand.nodeIdToDbId(4..4) {nodeId->
            nodeId.replaceAll("[a-zA-Z/_]","")
        }
        mockControl.demand.convertDateFromJson(6..6) {date->
            new Date()
        }
        testService.commonService = mockControl.createMock()

        //mock domain for tests
        mockDomain(Department)
        mockDomain(Project)
        def testDep = new Department(id: 1, name:"Dep1")
        assertNotNull "can't save department",testDep.save()
        def proj1 = new Project(id: 1, department: testDep, name: "Proj1", startDate: new Date())
        def proj2 = new Project(id: 2, department: testDep, name: "Proj2", startDate: new Date())
        mockDomain(Project,[proj1,proj2])
        assertEquals 2,Project.findAll().size()

        //test getProjectInfo(String projId)
        def result = testService.getProjectInfo("Project_1")
        assertNotNull "null result in getDepartmentInfo",result
        assertEquals "true",result.success
        assertEquals "Proj1",result.name

        //test updateProjectInfo(params)
        result = testService.updateProjectInfo([nodeId: "Project_1", name: "Proj1Updated"])
        assertNotNull "null result in updateProjectInfo",result
        assertNotNull "newName field is null",result.newName
        assertNotNull "nodeId field is null",result.nodeId
        assertEquals "true",result.success
        def foundProj = Project.findById(1)
        assertNotNull "found project is null",foundProj
        assertEquals "Proj1Updated",foundProj.name

        //test addProject(params)
        result = testService.addProject([parentNodeId: "Department_1", name: "Proj3"])
        assertNotNull "null result in addProject",result
        assertEquals "Department_1",result.parentNodeId
        assertNotNull "nodeId field is null",result.nodeId
        assertEquals "true",result.success

        foundProj = Project.findById(3)
        assertNotNull "found project is null",foundProj
        assertEquals "Proj3",foundProj.name
        assertEquals 3,Project.findAll().size()

        //test deleteProject(params)
        result = testService.deleteProject([nodeId: "Project_2",])
        assertNotNull "null result in deleteProject",result
        assertEquals "true",result.success

        foundProj = Department.findById(2)
        assertNull "project was not deleted",foundProj
        assertEquals 2,Project.findAll().size()

        //verify count of mocked methods calls
        mockControl.verify()
    }
}
